package com.kucan.recyclecard.net;

import static com.kucan.recyclecard.constants.Constant.TIME_OUT_EVENT_MSG;

import android.content.Context;
import android.os.Handler;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.kucan.recyclecard.bean.BannerBean;
import com.kucan.recyclecard.constants.Constant;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;

public class ApiImpl implements Api{
    private OkHttpEngine mOkHttpEngine;
    private Gson mGson;
    private Context mContext;
    private Handler mHandler = new Handler();

    public ApiImpl(Context context) {
        mOkHttpEngine = OkHttpEngine.getInstance(context);
        mGson = new Gson();
        mContext = context;
    }

    @Override
    public void getConfig(ApiCallBack<ApiResponse<String>> callBack) {
        HashMap<String, Object> map = new HashMap<>();
        try {
            mOkHttpEngine.getAsync(map, Api.CONFIG, new ApiCallBack<String>() {
                @Override
                public void onSuccess(String data) {
                    Type type = new TypeToken<ApiResponse<String>>() {
                    }.getType();
                    ApiResponse<String> bean = mGson.fromJson(data, type);
                    callBack.onSuccess(bean);
                }

                @Override
                public void onFailure(String errorCode, String message) {
                    callBack.onFailure(errorCode, message);
                }
            });
        } catch (Exception e) {
            callBack.onFailure(Constant.FAILED, TIME_OUT_EVENT_MSG);
            e.printStackTrace();
        }
    }

    @Override
    public void getBannerList(ApiCallBack<ApiResponse<List<BannerBean>>> callBack) {
        HashMap<String, Object> map = new HashMap<>();
        try {
            mOkHttpEngine.getAsync(map, Api.BANNER, new ApiCallBack<String>() {
                @Override
                public void onSuccess(String data) {
                    Type type = new TypeToken<ApiResponse<List<BannerBean>>>() {}.getType();
                    ApiResponse<List<BannerBean>> bean = mGson.fromJson(data, type);
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            callBack.onSuccess(bean);
                        }
                    });
                }

                @Override
                public void onFailure(String errorCode, String message) {
                    callBack.onFailure(errorCode, message);
                }
            });
        } catch (Exception e) {
            callBack.onFailure(Constant.FAILED, TIME_OUT_EVENT_MSG);
            e.printStackTrace();
        }
    }
}
